package com.example.hotelsystm.controller;

import com.example.hotelsystm.model.Hotel;
import com.example.hotelsystm.service.HotelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class HotelController {
    @Autowired
    private HotelService hotelService;

    //返回主页
//    @GetMapping("/")
//    public String viewHomePage(Model model){
//        model.addAttribute("listHotel",hotelService.getAllHotel());
//        return "index";
//    }

    @GetMapping("/")
    public String viewHomePage(Model model) {

        return findPaginated(1, "roomNo", "asc" ,model);
    }


    @GetMapping("/showNewHotelForm")
    public String showHotel(Model model){
        Hotel hotel = new Hotel();
        model.addAttribute("hotel",hotel);
        return "new_hotel";
    }

    @PostMapping("/saveHotel")
    public String saveHotel(@ModelAttribute("hotel") Hotel hotel){
        hotelService.saveHotel(hotel);
        return "redirect:/";
    }

    @GetMapping("/showNewHotelUpdate{id}")
    public String showFormForUpdate(@PathVariable(value = "id") long id,Model model){
        Hotel hotel = hotelService.getHotelByid(id);

        model.addAttribute("hotel",hotel);
        return "update_Host";
    }

    @GetMapping("/deleteHotel{id}")
    public String deleteHotel(@PathVariable(value = "id") long id){
        hotelService.deleteHotelByid(id);
        return "redirect:/";
    }

    //获取分页数据
    @GetMapping("/page/{pageNo}")
    public String findPaginated(@PathVariable (value = "pageNo") int pageNo,
                                @RequestParam("sortField") String sortField,
                                @RequestParam("sortDir") String sortDir,
                                Model model) {
        int pageSize = 5;

        Page<Hotel> page = hotelService.findPaginated(pageNo, pageSize, sortField, sortDir);
        List<Hotel> listHotel = page.getContent();



        model.addAttribute("currentPage", pageNo);
        model.addAttribute("totalPages", page.getTotalPages());
        model.addAttribute("totalItems", page.getTotalElements());

        model.addAttribute("sortField", sortField);
        model.addAttribute("sortDir", sortDir);
        model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc");

        model.addAttribute("listHotel", listHotel);


        return "index";
    }


    //搜索名字
    @GetMapping("/query{inpname}")
    public String query(@PathVariable(value = "inpname") String inpame,Model model){
        List<Hotel> listHotel = hotelService.findByRoomContaining(inpame);
        model.addAttribute("listHotel",listHotel);
        return "index";
    }
}
